﻿/**
 * 一级标题、二级标题
 *<div class="hdwiki_tmml"> 已经标题</div><div class="hdwiki_tmmll">二级标题</div>
 */
(function(E){

var Consts = E.consts,
	Utils = E.mod('Utils'),
	Menu = E.mod('Menu'),
	Selection = E.mod('Selection'),
	//标题类样式名称
	hdwikiTitle = {h1class:'hdwiki_tmml',h2class:'hdwiki_tmmll'},
	//标题模版
	titleMod = '<div class="[class]">[text]</div>';
// 目录快捷菜单
Menu.add('mouseup', {
	title: '目录快捷菜单',
	
	check: function( cursorElement ){
		var bool = false, node;
		if ( cursorElement && (typeof cursorElement === 'object') ){
			node = $(cursorElement);
			if( $.nodeName(cursorElement, 'div') && node.size() &&
				( hdwikiTitle.h1class == node.attr('class') ||
				  hdwikiTitle.h2class == node.attr('class')
				)
			){
				bool = true;
			}
		}
		return bool;
	},
	getHtml: function( cursorElement ){
		var html ='<a name="ShortcutMenu" method="totext">取消目录</a> <a name="ShortcutMenu" method="remove">删除目录</a>';
		return {className:'jqe-shortcut-menu', html:html};
	}
});
E.plugin("H1", {
	inserthtml: 'custom',
	icon: {
		width: 60,
		text: '一级目录',
		
		'default': {
			'H1': {XY:"none" }
		}
	},
	click: function( ){
		return Hn(hdwikiTitle.h1class, this);
	}
});
E.plugin("H2", {
	inserthtml: 'custom',
	icon: {
		width: 60,
		text: '二级目录',
		
		'default': {
			'H2': {XY:"none" }
		}
	},
	click: function( ){
		return Hn(hdwikiTitle.h2class, this);
	}
});

function Hn(className, Plugin){
	var html='',
		text = Plugin.getSelectionText(),
		ele = Plugin.getCursorElement(),
		dom = E.get('document'),
		isdiv = $.nodeName(ele, 'div'),
		jq = $(ele);
	if( isdiv &&
		$(ele).attr('class') == className) {
		var o = $(ele);
		html = $.trim(o.text()) ? o.html() : '';
		o.replaceWith( html );
	}else if( isdiv &&
		(jq.attr('class') == hdwikiTitle.h1class ||
			jq.attr('class') == hdwikiTitle.h2class)
		){
		jq.attr('class',className);
	}else if( check(text) ) {
		html = titleMod.replace(/\[class\]/g,className).replace(/\[text\]/g, text);
		Plugin.pasteHTML( html );
	}
	return 1;
}

function check(text){
	var msg = false;
	if(!text || $.trim(text).length<1) {
		msg = '不能设置空标题。';
	}else if(Utils.strlen(text) > 40){
		msg = '标题最多40个字符，一个汉字算2个字符。';
	}
	if(msg) {
		E.showError(msg);
		return false;
	}else {
		return true;
	}
}
})(jQEditor);